package com.example.java_chatroom.file;

import com.example.java_chatroom.api.MessageResponse;
import com.example.java_chatroom.model.Friend;
import com.example.java_chatroom.model.Message;
import com.example.java_chatroom.model.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class ChatUploadController {

    // 图片保存的目录（在 application.properties 中配置）
    @Value("${chat.upload.dir}")
    private String uploadDir;

    // 图片访问路径前缀
    @Value("${chat.upload.url-prefix}")
    private String urlPrefix;

    @PostMapping("/upload")
    public ResponseEntity<?> uploadImage(@RequestParam("image") MultipartFile file, HttpServletRequest req) {
        Map<String, Object> result = new HashMap<>();
        // 1. 先从会话中, 获取到 userId 是啥.
        HttpSession session = req.getSession(false);
        if (session == null) {
            // 当前用户会话不存在(未登录)
            // 直接返回一个空的列表即可.
            System.out.println("[getFriendList] session 不存在");
            return ResponseEntity.ok("[getFriendList] session 不存在");
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // 当前用户对象没在会话中存在
            System.out.println("[getFriendList] user 不存在");
            return ResponseEntity.ok("[getFriendList] user 不存在");
        }

        if (file.isEmpty()) {
            result.put("success", false);
            result.put("message", "上传文件为空");
            return ResponseEntity.badRequest().body(result);
        }

        // 获取文件原始名和后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = StringUtils.getFilenameExtension(originalFilename);
        if (suffix == null || !(suffix.matches("(?i)jpg|jpeg|png|gif|bmp|webp"))) {
            result.put("success", false);
            result.put("message", "只允许上传图片文件");
            return ResponseEntity.badRequest().body(result);
        }

        // 保存文件
        String fileName = UUID.randomUUID().toString() + "." + suffix;
        File savePath = new File(uploadDir, fileName);
        try {
            file.transferTo(savePath);
        } catch (IOException e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "服务器保存失败");
            return ResponseEntity.internalServerError().body(result);
        }
        String imageUrl = urlPrefix + "/" + fileName;

        // 保存图片消息到数据库
//        Message message = new Message();
//        message.setFromId(user.getUserId());
//        message.setSessionId(req.getSessionId());
//        message.setContent(req.getContent());
//        // 像自增主键, 还有时间这样的属性, 都可以让 SQL 在数据库中生成
//        messageMapper.add(message);

        result.put("success", true);
        result.put("url", imageUrl);
        return ResponseEntity.ok(result);
    }
}
